package com.hengtongxing.hejiayun.retorfit_manager;


import android.util.Log;


import com.hengtongxing.hejiayun.appconst.Constants;
import com.hengtongxing.hejiayun.bean.BaseResponseBean;
import com.hengtongxing.hejiayun.event.ReLoginEvent;
import com.hengtongxing.hejiayun.utils.JsonUtils;
import com.hengtongxing.hejiayun.widget.ViewLoading;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

/**
 *
 */
public abstract class ResponseObserver<T extends BaseResponseBean> implements Observer<ResponseBody>, IBaseResponse<T> {

    @Override
    public void onNext(ResponseBody responseBody) {
        try {
            String json = responseBody.string();
            Log.i("json=", json);
            T bean = getParseBean(json);
            ViewLoading.dismissProgress();
            if (bean == null) {
                BaseResponseBean baseBean = getParseResponseBean(json);
                if (baseBean != null) {
                    if ("300".equals(baseBean.getCode())) {
                        onReLogin(null, baseBean.getMsg());
                    } else {
                        onFailure(null, baseBean.getMsg(), Constants.ERROR_CODE_NO_DATA + "");
                    }
                } else {
                    onFailure(null, "数据异常", Constants.ERROR_CODE_NO_DATA + "");
                }
                return;
            }
            if ("300".equals(bean.getCode())) {
                onReLogin(bean, bean.getMsg());
            } else if ("200".equals(bean.getCode())) {
                onSuccessful(bean, bean.getMsg());
            } else {
                onFailure(bean, bean.getMsg(), bean.getCode());
            }
        } catch (IOException e) {
            e.printStackTrace();
            onFailure(null, "数据异常", Constants.ERROR_CODE_NO_DATA + "");
        }
    }

    @Override
    public void onError(Throwable throwable) {
        ViewLoading.dismissProgress();
        if (throwable.getMessage().contains("HTTP 413 Request Entity Too Large")) {
            onFailure(null, "上传文件过大", Constants.ERROR_CODE_NET + "");
        } else if (throwable.getMessage().contains("HTTP 500 Internal Server Error")) {
            onFailure(null, "服务器内部错误", Constants.ERROR_CODE_NET + "");
        } else if (throwable.getMessage().contains("Field map contained null value")) {
            onFailure(null, "传入参数有误", Constants.ERROR_CODE_NET + "");
        } else if (throwable.getMessage().contains("HTTP 502 Bad Gateway")) {
            onFailure(null, "HTTP 502 Bad Gateway", Constants.ERROR_CODE_NET + "");
        } else if (throwable.getMessage().contains("timeout")) {
            onFailure(null, "服务器请求超时", Constants.ERROR_CODE_NET + "");
        } else if (throwable.getMessage().contains("HTTP 404 Not Found")) {
            onFailure(null, "服务器请求错误", Constants.ERROR_CODE_NET + "");
        } else if (throwable.getMessage().contains("Failed to connect to")) {
            onFailure(null, "服务器无法访问", Constants.ERROR_CODE_NET + "");
        } else {
            onFailure(null, "网络不可用", Constants.ERROR_CODE_NET + "");
        }
        onComplete();
    }

    /**
     * 在一个正确运行的事件序列中,onCompleted() 和 onError() 有且只有一个，并且是事件序列中的最后一个。
     * 需要注意的是，onCompleted() 和 onError() 二者也是互斥的，即在队列中调用了其中一个，就不应该再调用另一个。
     */
    @Override
    public void onComplete() {

    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    private T getParseBean(String json) {
        Type type2 = getClass().getGenericSuperclass();
        Type[] types = ((ParameterizedType) type2).getActualTypeArguments();
        Class<T> mClass = (Class<T>) types[0];
        return JsonUtils.parse(json, mClass);
    }

    private BaseResponseBean getParseResponseBean(String json) {
        return JsonUtils.parse(json, BaseResponseBean.class);
    }
    //=================IBaseResponse 接口=====================

    @Override
    public void onReLogin(T bean, String msg) {
        EventBus.getDefault().post(new ReLoginEvent());
    }

}
